import BaseVenueProcessor from './BaseVenueProcessor.js';
import { getUPTennisSanXiSKYVenueSettings } from '../request.js';

/**
 * UPTennis三溪SKY店场地数据处理器
 */
export class UPTennisSanXiSKYProcessor extends BaseVenueProcessor {
  constructor() {
    super();
    this.venueName = 'UPTennis三溪SKY店';
  }

  /**
   * 获取UPTennis三溪SKY店场地预约设置
   * @param {Object} params - 查询参数 { date }
   * @returns {Promise} 请求Promise
   */
  async getVenueSettings(params = {}) {
    // 设置默认参数
    const defaultParams = {
      date: new Date().toISOString().split('T')[0].replace(/-/g, '%2F') // 默认今天，格式化为URL编码
    };
    
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getUPTennisSanXiSKYVenueSettings(requestData);
  }

  /**
   * 验证数据是否有效
   * @param {Array} data - 原始场地数据数组
   * @returns {boolean} 数据是否有效
   */
  validateData(data) {
    // 检查是否为数组且至少有一个元素
    if (!Array.isArray(data) || data.length === 0) {
      return false;
    }

    // 验证数组中每个元素的数据结构
    return data.every(item => 
      item && 
      item.data && 
      item.data.list && 
      Array.isArray(item.data.list) && 
      item.data.site_x && 
      Array.isArray(item.data.site_x)
    );
  }

  /**
   * 按场地名称分组
   * @param {Array} data - 原始场地数据数组
   * @returns {Map} 场地Map
   */
  groupVenues(data) {
    const venueMap = new Map();
    
    // 遍历数组中的每个数据源
    data.forEach(dataSource => {
      if (dataSource.data && dataSource.data.list) {
        dataSource.data.list.forEach(venue => {
          if (venue.site_name && venue.site_id) {
            // 如果场地已存在，保持原有信息；如果不存在，创建新的
            if (!venueMap.has(venue.site_name)) {
              venueMap.set(venue.site_name, {
                id: venue.site_id,
                name: venue.site_name,
                timeSlots: []
              });
            }
          }
        });
      }
    });
    
    return venueMap;
  }

  /**
   * 处理时间槽
   * @param {Map} venueMap - 场地Map
   * @param {Array} data - 原始场地数据数组
   */
  processTimeSlots(venueMap, data) {
    // 遍历数组中的每个数据源
    data.forEach(dataSource => {
      if (!dataSource.data || !dataSource.data.list) return;
      
      dataSource.data.list.forEach(venue => {
        const venueInfo = venueMap.get(venue.site_name);
        if (!venueInfo || !venue.site_data) return;
        
        venue.site_data.forEach(slot => {
          // status为2表示可预约
          if (slot.status === 2 && slot.start_time && slot.end_time) {
            venueInfo.timeSlots.push({
              time: `${slot.start_time}-${slot.end_time}`,
              startTime: slot.start_time,
              endTime: slot.end_time,
              beginDatetime: `${this.selectedDate} ${slot.start_time}:00`,
              endDatetime: `${this.selectedDate} ${slot.end_time}:00`,
              price: parseFloat(slot.price) || 0,
              isFree: true,
              id: slot.id || `${venue.site_id}_${slot.start_time}_${slot.end_time}`
            });
          }
        });
      });
    });
    
    // 对每个场地的时间槽按开始时间排序
    venueMap.forEach(venueInfo => {
      venueInfo.timeSlots.sort((a, b) => {
        const timeA = a.startTime.split(':').map(Number);
        const timeB = b.startTime.split(':').map(Number);
        return timeA[0] * 60 + timeA[1] - (timeB[0] * 60 + timeB[1]);
      });
    });
  }

  /**
   * 转换为场地列表格式
   * @param {Map} venueMap - 场地Map
   * @returns {Array} 场地列表
   */
  convertToVenueList(venueMap) {
    const venueList = [];
    
    venueMap.forEach((venue, name) => {
      if (venue.timeSlots.length > 0) {
        venueList.push({
          id: venue.id,
          name: venue.name,
          dataSource: 'UPTennis三溪SKY店',
          timeSlots: venue.timeSlots,
          totalSlots: venue.timeSlots.length,
          availableSlots: venue.timeSlots.filter(slot => slot.available).length,
          priceRange: this.calculatePriceRange(venue.timeSlots)
        });
      }
    });
    
    return venueList;
  }

  /**
   * 计算价格范围
   * @param {Array} timeSlots - 时间槽数组
   * @returns {Object} 价格范围 {min, max}
   */
  calculatePriceRange(timeSlots) {
    if (!timeSlots || timeSlots.length === 0) {
      return { min: 0, max: 0 };
    }
    
    const prices = timeSlots.map(slot => slot.price).filter(price => price > 0);
    if (prices.length === 0) {
      return { min: 0, max: 0 };
    }
    
    return {
      min: Math.min(...prices),
      max: Math.max(...prices)
    };
  }

  /**
   * 处理场地数据
   * @param {Object} data - 原始场地数据（合并后的数据）
   * @param {string} selectedDate - 选中的日期
   * @returns {Array} 处理后的场地列表
   */
  process(data, selectedDate) {
    this.selectedDate = selectedDate;
    if (!this.validateData(data)) {
      return [];
    }
    
    const venueMap = this.groupVenues(data);
    this.processTimeSlots(venueMap, data);
    return this.convertToVenueList(venueMap);
  }
}

export default UPTennisSanXiSKYProcessor;